#include "threadPool.h"

int initDirStack(dirStack_t *dirstack) {
    char root[] = "/home/hbin/code/linux";
    dirNode_t *bottom = (dirNode_t *)calloc(1, sizeof(dirNode_t));
    snprintf(bottom->data, sizeof(bottom->data), "%s", root);
    dirstack->bottom = bottom;
    dirstack->top = bottom;
    dirstack->size = 0;
    printf("root dir: \"%s\"\n", dirstack->bottom->data);
    return 0;
}

int pushDirStack(dirStack_t *dirstack, char *data) {
    dirNode_t *newNode = (dirNode_t *)calloc(1, sizeof(dirNode_t));
    snprintf(newNode->data, sizeof(newNode->data), "%s", data);
    dirstack->top->pnext = newNode;
    dirstack->top = newNode;
    ++dirstack->size;
    printf("pushed \"%s\"\n", dirstack->top->data);
    return 0;
}

int popDirStack(dirStack_t *dirstack) {
    if (dirstack->size != 0) {
        dirNode_t *cur = dirstack->bottom;
        while (cur->pnext != dirstack->top) {
            cur = cur->pnext;
        }
        printf("poped \"%s\"\n", dirstack->top->data);
        free(dirstack->top);
        cur->pnext = NULL;
        dirstack->top = cur;
        --dirstack->size;
    } else {
        printf("nothing to pop now!\n");
    }
    return 0;
}

int concatDirStack(dirStack_t *dirstack, char *pathname) {
    char result[4096] = {0};
    dirNode_t *cur = dirstack->bottom;
    int offset = 0;
    while (cur != NULL) {
        offset += snprintf(result + offset, sizeof(result) - offset, "%s", cur->data);
        cur = cur->pnext;
    }
    snprintf(pathname, sizeof(result), "%s", result);
    printf("concat result = \"%s\"\n", result);
    return 0;
}

int cleanDirStack(dirStack_t *dirstack) {
    // if (dirstack->size != 0) {
    // dirNode_t *cur = dirstack->bottom->pnext;
    // dirNode_t *cleaner = cur;
    // while (cur != NULL) {
    //   cur = cur->pnext;
    //   free(cleaner);
    //   cleaner = cur;
    // }
    // dirstack->bottom->pnext = NULL;
    // dirstack->top = dirstack->bottom;
    // dirstack->size = 0;
    // }
    while (dirstack->size != 0) {
        popDirStack(dirstack);
    }
    printf("dirStack cleaned!\n");
    return 0;
}

int destroyDirStack(dirStack_t *dirstack) {
    if (dirstack->size != 0) {
        cleanDirStack(dirstack);
    }
    free(dirstack->bottom);
    dirstack->bottom = NULL;
    dirstack->top = NULL;
    printf("dirStack destroyed!\n");
    return 0;
}

int copyDirStack(dirStack_t *copy, dirStack_t *paste) {
    cleanDirStack(paste);
    dirNode_t *cur = copy->bottom->pnext;
    for (int i = 0; i < copy->size; ++i) {
        pushDirStack(paste, cur->data);
        cur = cur->pnext;
    }
    return 0;
}
